﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

namespace Codedom_1 {

    delegate void myPrint();

    class Program {
        static void Main(string[] args) {
            for (int i = 0; i < 10; i++) {
                string FooSourcHeader = @"
                   using System;
                   class Foo {
                      static public void Print()
                      {";
                string FooSourceFooter = @"
                      }
                   }";

                string myPrint = FooSourcHeader
                               + @"Console.WriteLine(""Embedded Hello"");"
                               + @"Console.ReadKey();"
                               + FooSourceFooter;

                DateTime time1 = DateTime.Now;
                Assembly fooAssembly = CompileSource(myPrint);
                Type foo = fooAssembly.GetType("Foo");
                MethodInfo printMethod = foo.GetMethod("Print");
                myPrint print = (myPrint)Delegate.CreateDelegate(typeof(myPrint), printMethod);
                print();
                DateTime timer2 = DateTime.Now;
                TimeSpan ts = timer2 - time1;
                Console.WriteLine("Process Time (ms) :{0}", (int)ts.TotalMilliseconds);
            }
            Console.ReadKey();
        }


        private static Assembly CompileSource(string sourceCode) {
            CodeDomProvider cpd = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.GenerateExecutable = false;
            // Invoke compilation.
            CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);

            return cr.CompiledAssembly;
        }
    }
}
